我們可以透過結構體聲明來聲明包含不同資料類型的資料塊的形式。例如,人事檔案可能包含如下結構體:
struct tag {
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};
假設我們在磁碟檔案中有一堆這樣的結構,我們想要讀出每一個結構並列印出每個結構的名字和姓氏,以便我們可以在檔案中列出人員。其餘資訊將不會列印出來。我們將希望使用函數調用來進行此打印,並將指向手邊結構的指標傳遞給該函式。現在只使用一種結構。但要意識到目標是寫入函數,而不是讀取文件,大概我們知道如何做。
--------------- program 5.1 ------------------
#include <stdio.h>
#include <string.h>
struct tag {
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};
struct tag my_struct; /* declare the structure my_struct */
int main(void)
{
strcpy(my_struct.lname,"Jensen");
strcpy(my_struct.fname,"Ted");
printf("\n%s ",my_struct.fname);
printf("%s\n",my_struct.lname);
return 0;
}
-------------- end of program 5.1 --------------